package com.jpa.demo.repository.support;

import com.jpa.demo.repository.MyJpaRepository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

/**
 * 实现了操作的接口，但是本质上是调用EntityManager进行的操作
 * @param <T>
 * @param <ID>
 */
public class MySimpleJpaRepository<T, ID extends Serializable> implements MyJpaRepository<T, ID> {

    private final MyEntityManager entityManager;
    private final Class<T> entityClass;

    public MySimpleJpaRepository(Class<T> entityClass, MyEntityManager entityManager) {
        this.entityClass = entityClass;
        this.entityManager = entityManager;
    }

    @Override
    public T save(T entity) {
        return entityManager.persist(entity);
    }

    @Override
    public Optional<T> findById(ID id) {
        return Optional.ofNullable(entityManager.find(entityClass, id));
    }

    @Override
    public List<T> findAll() {
        return entityManager.findAll(entityClass);
    }

    @Override
    public void deleteById(ID id) {
        entityManager.delete(entityClass, id);
    }
}
